// 初始化游戏
let updateAERstate = 0;  // 全局状态变量，1表示正在升级空气动力学套件
let updateWTstate = 0;  // 全局状态变量，1表示已部署
let updatePeostate = 0;
let speed = 0.0008;
const PIT_STOP_DURATION_MAX = 4000;
document.addEventListener('DOMContentLoaded', function() {
    // 初始化资金
    if (localStorage.getItem('playerMoney') === null) {
        localStorage.setItem('playerMoney', 10000000);
        updateMoney();
    } else {
        updateMoney();
    }

    // 绑定菜单点击事件
    document.getElementById('goToRace').addEventListener('click', function() {
        startRace();
    });

    document.getElementById('updateAer').addEventListener('click', function() {
        // 预留空气动力学升级功能
        updateAer();
    });

    document.getElementById('updateWT').addEventListener('click', function(){
        // 预留风洞测试功能
        updateWT();
    });

    document.getElementById('updatePeo').addEventListener('click', function(){
        // 预留技师培训
        updatePeo();
    })
});

function formatMoney(num, chunkSize = 4, separator = ',') {
    //将playerMoney格式化，每四位加逗号。例：30000000 -> 3000,0000
  const str = num.toString();
  let result = [];
  // 从右往左分割
  for (let i = str.length; i > 0; i -= chunkSize) {
    const start = Math.max(0, i - chunkSize); // 防止负数索引
    result.unshift(str.slice(start, i)); // 从前面插入
  }
  return result.join(separator);
}

function updateMoney() {
    const playerMoney = localStorage.getItem('playerMoney');
    const formatted = formatMoney(playerMoney);
    document.getElementById("money").innerHTML = `￥${formatted}`;
}

function updateNowRun() {
    let text = '无';
    if (updateAERstate === 1){
        text = '空气动力学套件升级中';
    }else{
        if (updateWTstate === 2){
            text = '风洞测试中';
        }else{
            if (updatePeostate === 2){
                text = '技师培训中';
            }else{
                text = '无';
            }
        }
    }
    document.getElementById("nowRun").innerHTML = `当前进行项目：${text}`;
}

function getNowMinute() {
    const now = new Date();
    const minutes = now.getMinutes();
    return minutes;
}

function getRandom(min, max) {
    return Math.random() * (max - min) + min;
}

function checkAERstate() {
    if (updateAERstate === 1) {
        const nowMinute = getNowMinute();
        const updateAERtime = parseInt(localStorage.getItem('updateAERtime'));
        if (Math.abs(nowMinute - updateAERtime) >= 5) {
            updateAERstate = 0;
            localStorage.setItem('updateAERtime', 80);
            // alert('空气动力学套件升级完成');
            if (updateWTstate === 1){
                updateWTstate = 2;
                updateNowRun();
                localStorage.setItem('updateWTtime', getNowMinute());
                return;
            }
            speed = getRandom(0.0008,0.001);
            localStorage.setItem('playerSpeed', speed.toFixed(6))
            updateNowRun();
        }
    }
}

function checkWTstate() {
    if (updateWTstate === 2) {
        const nowMinute = getNowMinute();
        const updateWTtime = parseInt(localStorage.getItem('updateWTtime'));
        if (Math.abs(nowMinute - updateWTtime) >= 2) {
            updateWTstate = 0;
            localStorage.setItem('updateWTtime', 80);
            // alert('风洞测试完成');
            speed = 0.001;
            localStorage.setItem('playerSpeed', speed.toFixed(6))
            updateNowRun();
        }
    }
};

function cheakPeostate() {
    if (updatePeostate === 1) {
        const nowMinute = getNowMinute();
        const updatePeotime = parseInt(localStorage.getItem('updatePeotime'));
        if (Math.abs(nowMinute - updatePeotime) >= 2) {
            updatePeostate = 0;
            localStorage.setItem('updatePeotime', 80);
            updateNowRun();
            PIT_STOP_DURATION_MAX = getRandom(3000, 4000)
            localStorage.setItem('pitStopDurationMax', PIT_STOP_DURATION_MAX);
        }   
    } 
};

function startRace() {
    
    // 保存玩家参数到localStorage
    localStorage.setItem('playerSpeed', speed);
    localStorage.setItem('pitStopDurationMax', PIT_STOP_DURATION_MAX);
    
    // 初始化AI赛车标准速度(如果不存在)
    if (!localStorage.getItem('aiSpeeds')) {
        const aiSpeeds = 0.0008;
        // for (let i = 0; i < 5; i++) {
        //     // 生成随机速度(0.0003±10%)
        //     const baseSpeed = 0.0008;
        //     const variation = baseSpeed * 0.1; // 10%变化
        //     const randomSpeed = baseSpeed - variation + Math.random() * variation * 2;
        //     aiSpeeds.push(randomSpeed.toFixed(6));
        // }
        localStorage.setItem('aiSpeeds', JSON.stringify(aiSpeeds));
    }
    
    window.location.href = "./HTMLindex_race.html";
}

function updateAer(){
    const cost = 4500000;
    const currentMoney = parseInt(localStorage.getItem('playerMoney'));
    if (updateAERstate === 1){
        alert('空气动力学套件已在升级中');
        return;
    }
    if (updateWTstate === 2){
        alert('风洞测试正在进行，请稍后');
        return;
    }
    if (currentMoney >= cost) {
        alert('开始升级空气动力学套件，周期约5分钟');
        localStorage.setItem('playerMoney', currentMoney - cost);
        updateMoney();
        updateAERstate = 1;
        updateNowRun();
        localStorage.setItem('updateAERtime', getNowMinute());
    } else {
        alert('资金不足！');
    }
};

function updateWT() {
    const cost = 2000000;
    const currentMoney = parseInt(localStorage.getItem('playerMoney'));
    if (updateWTstate === 1) {
        alert('风洞测试已部署，将在空气动力学套件升级后启动')
    }
    if (updateAERstate === 0){
        alert('请先升级空气动力学套件，风洞测试会在升级完成后自动开始');
        return;
    }
    if (currentMoney >= cost) {
        alert('风洞测试已部署，将在空气动力学套件升级后启动');
        localStorage.setItem('playerMoney', currentMoney - cost);
        updateMoney();
        updateWTstate = 1;
    } else {
        alert('资金不足！');
    }
};

function updatePeo() {
    const cost = 3500000;
    const currentMoney = parseInt(localStorage.getItem('playerMoney'));
    if (updateAERstate === 1){
        alert('空气动力学套件正在升级，请稍后');
        return;
    }
    if (updateWTstate === 2){
        alert('风洞测试正在进行，请稍后');
        return;
    }
    if (currentMoney >= cost){
        alert('开始技师培训，周期约2分钟');
        localStorage.setItem('playerMoney', currentMoney - cost);
        updateMoney();
        updatePeostate = 1;
        updateNowRun();
        localStorage.setItem('updatePeotime', getNowMinute());
    }
}


function cheakUpdate() {
    checkAERstate();
    checkWTstate();

    setTimeout(cheakUpdate, 1000);
}

cheakUpdate();